package services;

import java.util.Collection;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import repositories.UserRepository;
import domain.User;
import forms.RegisterForm;

@Service
@Transactional
public class UserService {

	// Managed repository

	@Autowired
	private UserRepository userRepository;

	// Supporting services

	@Autowired
	private Md5PasswordEncoder encoder;

	// Simple CRUD methods

	public User create() {
		return new User();
	}

	public void save(User user) {
		Assert.notNull(user);
		String oldPassword = user.getUserAccount().getPassword();
		
		
		for(User u: userRepository.findAll()){
			Assert.isTrue(!user.getUserAccount().getUsername().equals(
					u.getUserAccount().getUsername()), "register.duplicated.username");
		}
		
		user.getUserAccount().setPassword(encoder.encodePassword(oldPassword, null));

		userRepository.save(user);
	}
	
	// Other business methods
	
	public Collection<User> findParticipantByEvent(int projectId){
		Collection<User> result;
		result = userRepository.findUserByProject(projectId);
		return result;
	}
	
	public User reconstruct(RegisterForm registerForm)
	{
		Assert.isTrue(registerForm.getTerminos(),"register.commit.terms.error");
		Assert.isTrue(registerForm.getUserAccount().getPassword().equals(registerForm.getRepeatPass()),"register.password.not.match");
		User participant = this.create();
		participant.setUserAccount(registerForm.getUserAccount());
		participant.setEmail(registerForm.getEmail());
		participant.setName(registerForm.getName());
		participant.setSurnames(registerForm.getSurnames());
		return participant;
	}
}
